﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BackupAssurance.Library.MEF;
using System.ComponentModel.Composition;
using BackupAssurance.Library.Interfaces;
using BackupAssurance.Library.ModelsDB;
using BackupAssurance.Library.XML;
using BackupAssurance.Library.Constants;

using System.IO;
using System.Diagnostics;

namespace BackupAssurance.impMountDrive
{

    [Export(typeof(IExecute)), ExportMetadata("PlugInType", "FileRun"), ExportMetadata("Version", 1)]
    public class piFileRun : IExecute
    {
        [Import]
        public IfLogger objLog { get; set; }

        string _name;
        string _strResult;
        string _output;
        Boolean _CaptureOutput;
        string _filename;
        string _parameter;
        string _programDirectory;

        public piFileRun()
        {

        }
        //<resource key="Action">Map</resource>


        public string Execute(pcJobAction jobaction, pcPlugInValue plugininfo)
        {

            _name = " START, Computer:" + System.Environment.MachineName + " FileRun v1,  Job ID:" + jobaction.Id.ToString() + " Plugin ID:" + plugininfo.Id.ToString() + Environment.NewLine + "       [" + plugininfo.PlugInText + "]";

            try
            {

                _strResult = "";
                _output = "";
                string progerror;
                string progconsole;

                Dictionary<string, string> objDic;
                objLog.WriteLine("Plugin Start: " + _name);

                objDic = fXMLParser.ConvertXMLtoDictionary(plugininfo.PlugInText);

                _CaptureOutput = Boolean.Parse(objDic[Constants.PLG_CAPTURE_OUTPUT]);
                _filename = objDic[Constants.PLG_PROGRAM_NAME];
                _parameter = objDic[Constants.PLG_PROGRAM_PARAMETERS];
                _programDirectory = objDic[Constants.PLG_PROGRAM_DIRECTORY];

                string combinedfilename;


                if (_programDirectory.Substring(_programDirectory.Length - 1, 1) != "\\")
                {
                    _programDirectory = _programDirectory + "\\";
                }

                try
                {
                    if ((_programDirectory != "") && !Directory.Exists(_programDirectory))
                    {
                        throw new Exception("The Program Directory does not exist. " + _programDirectory);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                combinedfilename = _programDirectory + _filename;

                try
                {
                    if (!File.Exists(combinedfilename))
                    {
                        throw new Exception("The executable program cannot be found. " + combinedfilename);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                objLog.WriteLine("Begin Program Execution --> " + DateTime.Now.ToString());

                ProcessStartInfo processStartInfo = new ProcessStartInfo(_filename, _parameter);

                processStartInfo.UseShellExecute = false;
                processStartInfo.ErrorDialog = false;
                processStartInfo.CreateNoWindow = true;

                if (_CaptureOutput == true)
                {
                    processStartInfo.RedirectStandardError = true;
                    processStartInfo.RedirectStandardInput = false;
                    processStartInfo.RedirectStandardOutput = true;
                }

                Process process = new Process();
                process.StartInfo = processStartInfo;
                bool processStarted = process.Start();

                if (_CaptureOutput == true)
                {
                    StreamReader errorReader = process.StandardError;
                    StreamReader outputReader = process.StandardOutput;

                    progerror = errorReader.ReadToEnd();
                    progconsole = outputReader.ReadToEnd();
                }

                process.WaitForExit();

                objLog.WriteLine("End Program Execution --< ");

                _strResult = Environment.NewLine + "Program [" + combinedfilename + "] executed successfully at " + DateTime.Now.ToString() + " " + Environment.NewLine + _name;
            }
            catch (Exception ex)
            {
                _output = _name + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
                objLog.WriteError(0, _output);
                throw new Exception(_output);
            }

            return _strResult;

        }


    }
}
